const express = require('express')
const app = express()
const axios = require('axios')
const cheerio = require('cheerio')

// respond with "hello world" when a GET request is made to the homepage
app.get('/loadUrlIcon', async function (req, res) {
  const http = req.query.url.split(':')[0]
  const url = req.query.url.endsWith('/') ? req.query.url.slice(0, req.query.url.length - 1) : req.query.url
  let { data } = await axios.get(url)
  let $ = cheerio.load(data)
  const links = $('link')
  const hrefs = []
  for (const iterator of links) {
    let href = $(iterator).attr('href')
    if (findImg(href)) {
        href = href.startsWith('//') ? `${http}:${href}` : href
        href.startsWith('/') ? hrefs.push(`${url}${href}`) : hrefs.push(href)
    }
  }
  function findImg (href) {
      const arr = ['svg', 'ico', 'png', 'jpg', 'jpeg']
      let status
      for (const key in arr) {
          if (href.endsWith(`.${arr[key]}`)) return true
      }
      return false
  }
  res.send(`
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        ${hrefs.map(href => `<img src="${href}" />`)}
    </body>
    </html>
  `)
})

app.listen(3000, () => console.log('app is runing on 3000 port'))